<template>
  <TeacherLayout>
    <el-card style="width: 100%; margin: 0 auto;" >
      <template #header>
        <div class="card-header">
          <span>考试管理</span>
          <el-button type="primary" @click="handleCreate">创建考试</el-button>
        </div>
      </template>
        <div class="search-bar">
          <el-input v-model="searchQuery" placeholder="请输入考试名称" prefix-icon="Search" style="width: 400px;" />
          <el-select v-model="statusFilter" placeholder="选择状态" style="width: 200px; margin-left: 10px;">
            <el-option label="全部状态" value=""></el-option>
            <el-option label="未开始" value="1"></el-option>
            <el-option label="进行中" value="2"></el-option>
            <el-option label="已结束" value="3"></el-option>
          </el-select>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
        </div>
        <el-table :data="examsData" style="width: 100%">
          <el-table-column prop="examId" label="考试ID" width="80"></el-table-column>
          <el-table-column prop="examName" label="考试名称" width="100"></el-table-column>
          <el-table-column prop="courseName" label="所属课程" width="80"></el-table-column>
          <el-table-column prop="totalScore" label="总分" width="60"></el-table-column>
          <el-table-column prop="duration" label="考试时长(分钟)" width="90"></el-table-column>
          <el-table-column prop="startTime" label="开始时间" width="170"></el-table-column>
          <el-table-column prop="endTime" label="结束时间" width="170"></el-table-column>
          <el-table-column prop="status" label="状态" width="70">
            <template #default="{ row }">
              <el-tag v-if="row.status === '未开始'" type="info">未开始</el-tag>
              <el-tag v-else-if="row.status === '进行中'" type="success">进行中</el-tag>
              <el-tag v-else type="danger">已结束</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="300">
            <template #default="{ row }">
              <el-button size="small" @click="handleView(row)">查看详情</el-button>
              <el-button type="primary" size="small" @click="handleEdit(row)">编辑考试</el-button>
              <el-button type="danger" size="small" @click="handleDelete(row.examId)">删除考试</el-button>
            </template>
          </el-table-column>
        </el-table>
        <div class="pagination">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            layout="total, sizes, prev, pager, next, jumper"
            :total="total"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
      </el-card>
    </TeacherLayout>

    <!-- 题目详情弹窗 -->
  <el-dialog
    v-model="dialogVisible"
    :title="`考试详情 - ${currentExam.examName}`"
    width="80%"
    top="5vh"
    :before-close="handleCloseDialog"
  >
    <div class="exam-info">
      <el-descriptions :column="3" border>
        <el-descriptions-item label="考试ID">{{ currentExam.examId }}</el-descriptions-item>
        <el-descriptions-item label="考试名称">{{ currentExam.examName }}</el-descriptions-item>
        <el-descriptions-item label="所属课程">{{ currentExam.courseName }}</el-descriptions-item>
        <el-descriptions-item label="总分">{{ currentExam.totalScore }}</el-descriptions-item>
        <el-descriptions-item label="考试时长">{{ currentExam.examDuration || '-' }}分钟</el-descriptions-item>
        <el-descriptions-item label="状态">{{ currentExam.status }}</el-descriptions-item>
        <el-descriptions-item label="开始时间">{{ currentExam.startTime }}</el-descriptions-item>
        <el-descriptions-item label="结束时间">{{ currentExam.endTime }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ currentExam.description || '-' }}</el-descriptions-item>
      </el-descriptions>
    </div>

    <div class="questions-section" style="margin-top: 20px;">
      <h3>题目列表</h3>
      <el-table :data="currentQuestions" style="width: 100%" max-height="400">
        <el-table-column type="index" label="#" width="50"></el-table-column>
        <el-table-column prop="questionContent" label="题目内容" min-width="200">
          <template #default="{ row }">
            <div class="question-content">{{ row.questionContent }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="typeId" label="题型" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.typeId === 1">单选题</el-tag>
            <el-tag v-else-if="row.typeId === 2">多选题</el-tag>
            <el-tag v-else-if="row.typeId === 3">判断题</el-tag>
            <el-tag v-else>其他</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="score" label="分数" width="80"></el-table-column>
        <el-table-column prop="difficulty" label="难度" width="80">
          <template #default="{ row }">
            <el-tag v-if="row.difficulty === '简单'" type="success">简单</el-tag>
            <el-tag v-else-if="row.difficulty === '中等'" type="warning">中等</el-tag>
            <el-tag v-else-if="row.difficulty === '困难'" type="danger">困难</el-tag>
            <span v-else>{{ row.difficulty }}</span>
          </template>
        </el-table-column>
        <el-table-column label="选项" min-width="200">
          <template #default="{ row }">
            <div v-if="row.typeId === 1 || row.typeId === 2">
              <div v-if="row.optionA">A. {{ row.optionA }}</div>
              <div v-if="row.optionB">B. {{ row.optionB }}</div>
              <div v-if="row.optionC">C. {{ row.optionC }}</div>
              <div v-if="row.optionD">D. {{ row.optionD }}</div>
            </div>
            <div v-else>-</div>
          </template>
        </el-table-column>
        <el-table-column prop="correctAnswer" label="正确答案" width="100"></el-table-column>
      </el-table>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="handleCloseDialog">关闭</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search } from '@element-plus/icons-vue'
import { get } from '../../utils/api'
import TeacherLayout from '../../components/teacher/TeacherLayout.vue'

// 定义考试和题目类型
interface Question {
  score: number
  typeId: number
  questionContent: string
  optionA: string | null
  optionB: string | null
  optionC: string | null
  optionD: string | null
  correctAnswer: string
  difficulty: string
}

interface Exam {
  examId: number
  examName: string
  courseId: number
  courseName: string
  startTime: string
  endTime: string
  totalScore: number
  examDuration: number | null
  description: string
  status: number
  questionList: Question[]
  [key: string]: any // 允许其他属性
}

const router = useRouter()

// 考试数据
const examsData = ref<Exam[]>([])
const searchQuery = ref('')
const statusFilter = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 题目详情弹窗相关
const dialogVisible = ref(false)
const currentQuestions = ref<Question[]>([])
const currentExam = ref<Partial<Exam>>({})

// 获取当前教师ID
const getCurrentTeacherId = async () => {
  try {
    const response = await get('/teacher/get/my')
    if (response.code === 200) {
      return response.data // 返回教师ID
    } else {
      ElMessage.error(response.msg || '获取教师信息失败')
      return null
    }
  } catch (error) {
    console.error('获取教师信息失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    return null
  }
}

// 获取考试列表
const fetchExams = async () => {
  try {
    // 首先获取教师ID
    const teacherId = await getCurrentTeacherId()
    if (!teacherId) {
      ElMessage.error('未获取到教师信息')
      return
    }
    
    const response = await get(`/exam/query/teacherId?teacherId=${teacherId}`)
    
    if (response.code === 200) {
      // 处理考试数据
      examsData.value = response.data.map((exam: any) => {
        // 格式化状态
        let statusLabel = '未知'
        switch (exam.status) {
          case 0: statusLabel = '未开始'; break
          case 1: statusLabel = '进行中'; break
          case 2: statusLabel = '已结束'; break
          default: statusLabel = '未知'
        }
        
        // 格式化时间
        const formatTime = (timeStr: string) => {
          return timeStr ? timeStr.replace('T', ' ').substring(0, 19) : ''
        }
        
        return {
          ...exam,
          startTime: formatTime(exam.startTime),
          endTime: formatTime(exam.endTime),
          status: statusLabel,
          duration: exam.examDuration || '-'
        }
      })
      total.value = response.dataCount || response.data.length
    } else {
      ElMessage.error(response.msg || '获取考试列表失败')
    }
  } catch (error) {
    console.error('获取考试列表失败:', error)
    ElMessage.error('网络错误，请稍后重试')
  }
}

const handleCreate = () => {
  router.push('/teacher/exam/add')
}

const handleView = (exam: Exam) => {
  // 显示考试详情和题目列表
  currentExam.value = exam
  currentQuestions.value = exam.questionList || []
  dialogVisible.value = true
}

const handleEdit = (row: Exam) => {
  // 跳转到编辑考试页面
  router.push(`/teacher/exam/edit/${row.examId}`)
}

const handleDelete = (examId: number) => {
  // 删除功能
  ElMessageBox.confirm('确定要删除该考试吗？', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    // 这里应该调用删除API
    ElMessage.success('删除成功')
    // 重新获取数据
    fetchExams()
  }).catch(() => {
    // 取消删除
  })
}

const handleSearch = () => {
  // 搜索功能
  ElMessage.info(`搜索：${searchQuery.value}，状态：${statusFilter.value}`)
  // 实际项目中这里应该重新调用API进行搜索
  fetchExams()
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  fetchExams()
}

const handleCurrentChange = (current: number) => {
  currentPage.value = current
  fetchExams()
}

// 关闭弹窗
const handleCloseDialog = () => {
  dialogVisible.value = false
  currentQuestions.value = []
  currentExam.value = {}
}

// 页面加载时获取数据
onMounted(() => {
  fetchExams()
})
</script>

<style scoped>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: bold;
  text-align: center;
}

.search-bar {
  margin-bottom: 20px;
  display: flex;
  gap: 10px;
  align-items: center;
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.question-content {
  white-space: pre-wrap;
  word-break: break-all;
}

.dialog-footer {
  text-align: right;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .search-bar {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-bar .el-input,
  .search-bar .el-select {
    width: 100% !important;
    margin-left: 0 !important;
    margin-bottom: 10px;
  }
  
  .card-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 10px;
  }
  
  .pagination {
    justify-content: center;
  }
}
</style>